package com.usoft;

import akka.dispatch.ExecutionContexts;
import akka.dispatch.Futures;
import akka.dispatch.Mapper;
import scala.concurrent.Await;
import scala.concurrent.ExecutionContextExecutorService;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;

import java.util.concurrent.Executors;

/**
 * Created by liyanxin on 2015/1/8.
 */
public class FutureDemo5 {

    public static void main(String args[]) throws Exception {

        final ExecutionContextExecutorService ec = ExecutionContexts.fromExecutorService(
                Executors.newCachedThreadPool());
        final Future<String> f1 = Futures.successful("How");
        final Future<String> f2 = Futures.successful("are");
        final Future<String> f3 = Futures.successful("you");

        //如果要对多个Future的结果进行处理，需要用flatMap
        //本例中对f1、f2、f3返回的结果用空格连接成“How are you”
        Future<String> fr = f1.flatMap(new Mapper<String, Future<String>>() {
            public Future<String> apply(final String s) {
                return f2.flatMap(new Mapper<String, Future<String>>() {
                    @Override
                    public Future<String> apply(final String s2) {
                        return f3.map(new Mapper<String, String>() {
                            @Override
                            public String apply(String s3) {
                                return s + " " + s2 + " " + s3;
                            }
                        }, ec);
                    }
                }, ec);
            }
        }, ec);

        /**
         * 如下是scala的写法
         *  val future1 = for {
         *      a: String <- actor ? "How" // returns How
         *      b: String <- actor ? "are" // returns "are"
         *      c: String <- actor ? "you" // returns "you"
         *} yield a + " " + b + "" + c
         */
        //阻塞式
        System.out.println(Await.result(fr, Duration.create(5, "s")));
    }

}
